package com.fowo.api.syncAmazon.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fowo.api.entity.AmzAdvertisAuthInfo;
import com.fowo.api.entity.TmpAdvertiserInvoices;
import com.fowo.api.entity.TmpAdvertiserInvoicesCampaign;
import com.fowo.api.mapper.AmzAdvertisAuthInfoMapper;
import com.fowo.api.mapper.TmpAdvertiserInvoicesMapper;
import com.fowo.api.service.impl.TmpAdvertiserInvoicesCampaignServiceImpl;
import com.fowo.api.service.impl.TmpAdvertiserInvoicesServiceImpl;
import com.fowo.api.syncAmazon.core.AmazonAdvertAuthAction;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Component
@Slf4j
public class AdvertiserInvoicesServiceImpl {
    @Resource
    private AmazonAdvertAuthAction amazonAdvertAuthAction;
    @Resource
    private AmzAdvertisAuthInfoMapper amzAdvertisAuthInfoMapper;
    @Resource
    private TmpAdvertiserInvoicesServiceImpl tmpAdvertiserInvoicesService;
    @Resource
    private TmpAdvertiserInvoicesCampaignServiceImpl tmpAdvertiserInvoicesCampaignService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    @Transactional
    public void syncInvoices(){
        amazonTmpMapper.deleteTmpAdvertiserInvoices();
        amazonTmpMapper.deleteTmpAdvertiserInvoicesCampaign();
        getInvoicesData();
        amazonTmpMapper.updateAmazonAdvertiserInvoices();
        amazonTmpMapper.insertAmazonAdvertiserInvoices();
        amazonTmpMapper.insertAmazonAdvertiserInvoicesCampaign();
    }

    /**
     * 获取广告发票
     */
    public void getInvoicesData(){
        final List<AmzAdvertisAuthInfo> amzAdvertisAuthInfos = amzAdvertisAuthInfoMapper.selectList(null);
        Map<String,Object> query = new HashMap<>();
        Calendar cstart=Calendar.getInstance();
        cstart.add(Calendar.DATE,-5);
        String startDate = DateUtil.format(cstart.getTime(), DatePattern.PURE_DATE_PATTERN);
        query.put("startDate",startDate);
        query.put("count",100);
        for(AmzAdvertisAuthInfo amzAdvertisAuthInfo : amzAdvertisAuthInfos){
            String token = amazonAdvertAuthAction.getToken(amzAdvertisAuthInfo.getRefreshToken());
            final Object result = amazonAdvertAuthAction.getInvoices(token,amzAdvertisAuthInfo.getProfileId().toString(),query);
            JSONObject invoices = JSONUtil.parseObj(result);
            if(invoices.getStr("status").equals("success")){
                final JSONObject payload = invoices.getJSONObject("payload");
                final JSONArray invoiceSummaries = payload.getJSONArray("invoiceSummaries");
                List<TmpAdvertiserInvoices> tmpList = buildInvoicesData(invoiceSummaries,amzAdvertisAuthInfo.getSid());
                String nextCursor = payload.getStr("nextCursor");
                if(StrUtil.isNotBlank(nextCursor)){
                    tmpList.addAll(getNextInvoices(token,amzAdvertisAuthInfo.getProfileId().toString(),nextCursor,amzAdvertisAuthInfo.getSid()));
                }
                //广告活动
                List<TmpAdvertiserInvoicesCampaign> campaignList = new ArrayList<>();
                getInvoiceByInvoiceId(token,amzAdvertisAuthInfo.getProfileId().toString(),tmpList,campaignList);

                tmpAdvertiserInvoicesService.saveBatch(tmpList);
                tmpAdvertiserInvoicesCampaignService.saveBatch(campaignList);
            }
        }
    }

    /**
     * 获取下一页广告发票
     * @param token
     * @param profileId
     * @param nextCursor
     * @param sid
     * @return
     */
    public List<TmpAdvertiserInvoices> getNextInvoices(String token,String profileId,String nextCursor,Long sid ){
        List<TmpAdvertiserInvoices> tmpList = new ArrayList<>();
        Map<String,Object> query = new HashMap<>();
        query.put("cursor",nextCursor);
        final Object result = amazonAdvertAuthAction.getInvoices(token,profileId,query);
        JSONObject invoices = JSONUtil.parseObj(result);
        if(invoices.getStr("status").equals("success")){
            final JSONObject payload = invoices.getJSONObject("payload");
            final JSONArray invoiceSummaries = payload.getJSONArray("invoiceSummaries");
            tmpList = buildInvoicesData(invoiceSummaries,sid);
            String next = payload.getStr("nextCursor");
            if(StrUtil.isNotBlank(next)){
                tmpList.addAll(getNextInvoices(token,profileId,next,sid));
            }
        }
        return tmpList;
    }

    /**
     * 构建广告发票临时表数据
     * @param invoiceSummaries
     * @param sid
     * @return
     */
    public List<TmpAdvertiserInvoices> buildInvoicesData(JSONArray invoiceSummaries,Long sid){
        List<TmpAdvertiserInvoices> list = new ArrayList<>();
        for(int i = 0 ; i < invoiceSummaries.size() ; i++){
            JSONObject jsonObject = invoiceSummaries.getJSONObject(i);
            TmpAdvertiserInvoices tmp = new TmpAdvertiserInvoices();
            tmp.setCreateTime(new Date());
            tmp.setLastUpdateTime(new Date());
            tmp.setInvoiceId(jsonObject.getStr("id"));
            tmp.setPaymentMethod(jsonObject.getStr("paymentMethod"));
            tmp.setStatus(jsonObject.getStr("status"));
            String fromDate = jsonObject.getStr("fromDate");
            tmp.setFromDate(DateUtil.parse(fromDate, DatePattern.PURE_DATE_FORMAT));
            String toDate = jsonObject.getStr("toDate");
            tmp.setToDate(DateUtil.parse(toDate, DatePattern.PURE_DATE_FORMAT));
            final JSONObject amountDue = jsonObject.getJSONObject("amountDue");
            tmp.setAmount(amountDue.getBigDecimal("amount"));
            tmp.setCurrency(amountDue.getStr("currencyCode"));
            String invoiceDate = jsonObject.getStr("invoiceDate");
            tmp.setInvoiceDate(DateUtil.parse(invoiceDate, DatePattern.PURE_DATE_FORMAT));
            tmp.setSid(sid);
            list.add(tmp);
        }
        return list;
    }

    public void getInvoiceByInvoiceId(String token,String profileId,List<TmpAdvertiserInvoices> tmpList,List<TmpAdvertiserInvoicesCampaign> campaignList){
        for(TmpAdvertiserInvoices invoices : tmpList){
            Map<String,Object> query = new HashMap<>();
            query.put("path",invoices.getInvoiceId());
            Object invoiceInfo = amazonAdvertAuthAction.getInvoiceByInvoiceId(token, profileId, query);
            final JSONObject jsonObject = JSONUtil.parseObj(invoiceInfo);
//            System.out.println(JSONUtil.parseObj(invoiceInfo));

            final String status = jsonObject.getStr("status");
            if(StrUtil.equals(status,"success")){
                final JSONObject payload = jsonObject.getJSONObject("payload");
                //汇总
                final JSONObject invoiceSummary = payload.getJSONObject("invoiceSummary");
                invoices.setPaymentMethod(invoiceSummary.getStr("paymentMethod"));

//            final JSONObject payerContactInformation = payload.getJSONObject("payerContactInformation");
//            final JSONObject address = payerContactInformation.getJSONObject("address");

                final JSONArray invoiceLines = payload.getJSONArray("invoiceLines");
                for(int i = 0 ; i < invoiceLines.size() ; i++){
                    TmpAdvertiserInvoicesCampaign campaign = new TmpAdvertiserInvoicesCampaign();
                    campaign.setCreateTime(new Date());
                    campaign.setLastUpdateTime(new Date());
                    final JSONObject object = invoiceLines.getJSONObject(i);
                    campaign.setInvoiceId(invoices.getInvoiceId());
                    campaign.setCampaignName(object.getStr("campaignName"));//广告活动
                    campaign.setCampaignId(object.getStr("campaignId"));//活动id
                    campaign.setAdsType(object.getStr("programName"));//广告类型
                    campaign.setPriceType(object.getStr("priceType"));//计价方式
                    campaign.setCostEventCount(object.getInt("costEventCount"));//点击量
                    final JSONObject cost = object.getJSONObject("cost");
                    campaign.setCostAmount(cost.getBigDecimal("amount"));//费用
                    campaign.setCurrency(cost.getStr("currencyCode"));//币种
                    campaign.setCostPerUnit(object.getBigDecimal("costPerUnit"));//平均点击单价

                    campaignList.add(campaign);
                }
            }
        }
    }
}
